// 对状态存储对象进行模块化管理
import { defineStore } from 'pinia'
// 引入用户登录接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user/index.ts'
// 引入interface数据类型
import { loginForm, loginResponse, userInfoResponse } from '@/api/user/user.ts'
import { UserState } from './type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '../../utils/token'
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes.ts'
import _ from 'lodash'
import router from '@/router'
// 定义一个方法用于过滤出当前用户拥有哪些动态路由组件
function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
const useUserStore = defineStore('userStore', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
      buttons: [], //按钮权限控制
    }
  },
  actions: {
    async userLogin(loginForm: loginForm) {
      let result: loginResponse = await reqLogin(loginForm)
      let { code, data, message } = result
      console.log(data)
      if (code == 200) {
        // 请求成功
        this.token = data
        SET_TOKEN(data)
        // 给vue组件发送消息通知
        return 'ok'
      } else {
        return Promise.reject(new Error(message))
      }
    },
    // 获取当前登录用户相关信息
    async getUserInfo() {
      let result: userInfoResponse = await reqUserInfo()
      console.log(result)
      const { code, data, message } = result
      if (code == 200) {
        const { name, avatar, routes, buttons } = data
        // 将当前用户的路由表和所有的动态路由表进行对比，然后判断出当前用户有哪些动态路由
        // 为了不影响下个用户的异步路由，这里使用深拷贝复制一份异步路由
        const userAsyncRoute = filterAsyncRoute(_.cloneDeep(asyncRoute), routes)
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, ...anyRoute]
        //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
        ;[...userAsyncRoute, ...anyRoute].forEach((route: any) => {
          // 将异步路由注册到路由表中
          router.addRoute(route)
        })
        this.buttons = buttons
        this.username = name
        this.avatar = avatar
        return 'ok'
      } else {
        return Promise.reject('获取用户信息失败')
      }
    },
    // 退出登录，清空当前仓库中的数据和本地存储的token信息
    async logout() {
      let result = await reqLogout()
      const { code, message } = result
      if (code == 200) {
        this.$state.username = ''
        this.$state.avatar = ''
        this.$state.token = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject('退出登录失败')
      }
    },
  },
  getters: {},
})
export default useUserStore
